package com.workcenter.app;

import com.ppcodes.core.data.DXml;
import com.ppcodes.core.data.DXmlHead;
import com.ppcodes.core.utils.UtiDialogsFactory;
import com.workcenter.base.UIBase;
import com.workcenter.entity.NetClient;
import com.workcenter.entity.Session;
import com.workcenter.entity.PubConst;
import com.workcenter.entity.UrlParams;
import com.workcenter.entity.model.EUser;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;

public class UILogin extends UIBase
{
   private Button btnLogin;
   private EditText edtUser;
   private EditText edtPwd;
   private CheckBox cbkShowPwd;
   private CheckBox cbkRemember;

   private void InitControls()
   {
	  btnLogin = (Button) findViewById(R.id.btn_login);
	  edtUser = (EditText) findViewById(R.id.edtUser_login);
	  edtPwd = (EditText) findViewById(R.id.edtPwd_login);
	  cbkShowPwd = (CheckBox) findViewById(R.id.ckbShowPwd_login);
	  cbkRemember = (CheckBox) findViewById(R.id.ckbRemember_login);
   }

   private void InitControlsEvent()
   {
	  btnLogin.setOnClickListener(new View.OnClickListener()
	  {
		 @Override
		 public void onClick(View v)
		 {
			if (edtUser == null || edtUser.getText().toString().trim().equals(""))
			{
			   UtiDialogsFactory.getInstance().ShowToastInfoShort(UILogin.this, getString(R.string.login_user_not_empty));
			}
			else if (edtPwd == null || edtPwd.getText().toString().trim().equals(""))
			{
			   UtiDialogsFactory.getInstance().ShowToastInfoShort(UILogin.this, getString(R.string.login_pwd_not_empty));
			}
			else
			{
			   executeAsyncTask(PubConst.TaskName.LOGIN);
			}
		 }
	  });

	  cbkShowPwd.setOnCheckedChangeListener(new OnCheckedChangeListener()
	  {
		 @Override
		 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
		 {
			if (isChecked)
			{
			   // edtUserKey.setInputType(0x90);//密码可见
			   edtPwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
			}
			else
			{
			   // edtUserKey.setInputType(0x81);//密码不可见
			   edtPwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
			}
		 }
	  });
   }

   @Override
   protected void onCreate(Bundle savedInstanceState)
   {

	  super.onCreate(savedInstanceState);
	  setContentView(R.layout.login);

	  try
	  {
		 InitControls();
		 InitControlsEvent();

		 SharedPreferences userSetting = getSharedPreferences(PubConst.Setting.Setting, Activity.MODE_PRIVATE);
		 Boolean isRemember = userSetting.getBoolean(PubConst.Setting.IS_REMEMBER, false);

		 if (isRemember)
		 {
			String lastUserName = userSetting.getString(PubConst.Setting.LastUserName, "");
			cbkRemember.setChecked(true);
			edtUser.setText(lastUserName);
			if (!lastUserName.equals(""))
			{
			   edtPwd.setFocusable(true);
			   edtPwd.requestFocus();
			}
		 }
	  }
	  catch (Exception e)
	  {

	  }

   }

   @Override
   protected void onDestroy()
   {
	  // 保存上一次用过的用户名
	  try
	  {
		 SharedPreferences.Editor editor = getSharedPreferences(PubConst.Setting.Setting, Activity.MODE_PRIVATE).edit();
		 if (cbkRemember.isChecked())
		 {
			editor.putBoolean(PubConst.Setting.IS_REMEMBER, true);
		 }
		 else
		 {
			editor.putBoolean(PubConst.Setting.IS_REMEMBER, false);
		 }
		 editor.putString(PubConst.Setting.LastUserName, edtUser.getText().toString().trim());
		 editor.commit();
	  }
	  catch (Exception e)
	  {
		 // Log.e(PubConst.Tag.ERROR, "onDestroy()", e);
	  }

	  super.onDestroy();
   }

   @Override
   public boolean onKeyDown(int keyCode, KeyEvent event)
   {
	  if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0)
	  {
		 UtiDialogsFactory.getInstance().ShowOKCancelAlertDialog(UILogin.this, getString(R.string.dialog_tips), getString(R.string.dialog_are_you_sure_exit), new DialogInterface.OnClickListener()
		 {
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
			   dialog.dismiss();
			   System.exit(0);
			}
		 });
	  }
	  else if (keyCode == KeyEvent.KEYCODE_ENTER)
	  {
		 if (edtUser.isFocused())
		 {
			edtPwd.setFocusable(true);
			edtPwd.requestFocus();
			edtPwd.setFocusableInTouchMode(true);
		 }
	  }
	  return true;
   }

   @Override
   public void onAsyncTaskStart(String taskName, Object[] params)
   {
	  UtiDialogsFactory.getInstance().ShowLoadingDialogNoTitle(UILogin.this, getString(R.string.login_logining));
   }

   @Override
   public Object onAsyncTaskInBackground(String taskName, Object[] params) throws Exception
   {
	  try
	  {
		 if (taskName != null && taskName.equals(PubConst.TaskName.LOGIN))
		 {
            return NetClient.Login(edtUser.getText().toString().trim(), edtPwd.getText().toString().trim());
		 }
	  }
	  catch (Exception e)
	  {
		 if (Session.getInstance().IsDEBUG())
		 {
			Log.e("ERROR", "UILogin_onAsyncTaskInBackground(taskName, params) ", e);
		 }
	  }

	  return null;
   }

   @Override
   public void onAsyncTaskEnd(String taskId, String taskName, Object[] params, Object result)
   {
	  try
	  {	
		 UtiDialogsFactory.getInstance().DismissLoadingDialog();
		 if(taskName.equals(PubConst.TaskName.LOGIN))
		 {
            if(result!=null)
            {
               DXml data=(DXml)result;
               if(data.getHead().GetFieldValue(UrlParams.RspCode).equals(UrlParams.SuccessCode))
               {
				  EUser user = new EUser();
				  user.setUserID(data.getBody().GetFieldInt32("UserID"));
				  user.setLoginName(data.getBody().GetFieldValue("LoginName"));
				  user.setPassword(data.getBody().GetFieldValue("Password"));
				  user.setUserName(data.getBody().GetFieldValue("UserName"));
				  user.setUserParam(data.getBody().GetFieldValue("UserParam"));
				  user.setUserSite(data.getBody().GetFieldValue("UserSite"));

				  Session.getInstance().setUserInfo(user);

				  // 登录成功后更新上次登录用户名
				  SharedPreferences.Editor editor = getSharedPreferences(PubConst.Setting.Setting, Activity.MODE_PRIVATE).edit();
				  editor.putString(PubConst.Setting.LastLoginUserName, user.getLoginName());
				  editor.commit();

				  Intent intent = new Intent();
				  intent.setClass(UILogin.this, UIMain.class);
				  startActivity(intent);
				  finish();
               }
               else 
			   {
   			      UtiDialogsFactory.getInstance().ShowToastInfoShort(UILogin.this, data.getHead().GetFieldValue(UrlParams.RspMsg));
			   }
			}
			else
			{
			   UtiDialogsFactory.getInstance().ShowToastInfoShort(UILogin.this, getString(R.string.login_wrong_net));
			}
		 }
	  }
	  catch (Exception e)
	  {
		 UtiDialogsFactory.getInstance().ShowOKAlertDialog(UILogin.this, getString(R.string.dialog_tips), getString(R.string.login_wrong_net));
	  }

   }

}
